using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using SF.Code.Extension.CollectionsHelper;

namespace SG.Productivity.DesktopControlPanel.ParallelQuery
{
    public class QueryRecord : IEnumerable<QueryMatch>
    {
        private readonly ReadOnlyArray<QueryMatch> _results;

        private QueryRecord(params QueryMatch[] results)
        {
            _results = results;
        }

        public IReadOnlyArray<QueryMatch> Results { get { return _results; } }  

        public static implicit operator QueryRecord(JObject serialized)
        {
            var resultsJArray = (JArray) serialized["results"];
            var count = resultsJArray.Count;
            var orderedResultSet = new QueryMatch[count];

            for (var i = 0; i < count; i++)
            {
                orderedResultSet[i] = resultsJArray[i].ToObject<QueryMatch>();
            }

            return new QueryRecord(orderedResultSet);
        }

        public IEnumerator<QueryMatch> GetEnumerator()
        {
            return Results.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}